//活动
const Router = require('koa-router')
const router = new Router()
const orm = require('../utils/mysql')
const activity = require('../model/activity')
const querystring = require('querystring');

router.prefix('/activity')

router.get('/all', async (ctx, next) => {
	var query = () => {
		return new Promise((resolve, rject) => {

			var Activity = orm.db.define("activity", activity, {
				methods: {
					fullName: function() {
						return this.name + ' ' + this.surname;
					}
				},
				validations: {
					age: orm.enforce.ranges.number(18, undefined, "under-age")
				}
			});
			Activity.find({

			}, function(err, activity) {
				if (err) {
					resolve({
						code: 400,
						msg: err
					})
				}
				resolve({
					code: 200,
					obj: activity
				})
			})
		})
	}
	var result = await query();
	ctx.body = result;
});

router.post('/add', async (ctx, next) => {

	var newAct = querystring.parse(ctx.req._parsedUrl.query);
	console.log(typeof(newAct))
	var query = () => {
		return new Promise((resolve, rject) => {
			var Activity = orm.db.define("activity", activity, {
				methods: {
					fullName: function() {
						return this.name + ' ' + this.surname;
					}
				},
				validations: {
					age: orm.enforce.ranges.number(18, undefined, "under-age")
				}
			});
			var json = {
				name: newAct.name,
				yn: 0
			}
			Activity.create(json, function(err, activity) {
				if (err) {
					resolve({
						code: 400,
						msg: "添加失败,检测参数是否正常"
					})
				}
				Activity.find({

				}, function(err, activity) {
					if (err) {
						resolve({
							code: 400,
							msg: err
						})
					}
					resolve({
						code: 200,
						obj: activity
					})
				})

			})
		})
	}
	var result = await query();
	ctx.body = result;
});

router.get('/change', async (ctx, next) => {
	var newAct = querystring.parse(ctx.req._parsedUrl.query);
	console.log(typeof(newGoods))
	var query = () => {
		return new Promise((resolve, rject) => {
			var Activity = orm.db.define("activity", activity, {
				methods: {
					fullName: function() {
						return this.name + ' ' + this.surname;
					}
				},
				validations: {
					age: orm.enforce.ranges.number(18, undefined, "under-age")
				}
			});

			Activity.find({
				id: newAct.id
			}, function(err, activity) {
				if (err) {
					resolve({
						code: 400,
						msg: err
					})
				}
				activity[0].yn = newAct.yn;
				activity[0].save(function(err) {
					if (err) {
						resolve({
							code: 400,
							msg: err
						})
					} else {
						resolve({
							code: 200,
							msg: '修改成'
						})

					}

				})


			})

		})
	}
	var result = await query();
	ctx.body = result;
});



module.exports = router